#include<stdio.h>
#include <stdlib.h>
#include<conio.h>
#include<windows.h>
#define random(x) (rand()%x)

int high,width;		//¶¨ÒåÓÎÏ·»­Ãæ 
int ball_x,ball_y;		//¶¨ÒåÐ¡ÇòÎ»ÖÃ 
int ball_vx,ball_vy;		//¶¨ÒåÐ¡ÇòµÄËÙ¶È
int position_x,position_y;		//¶¨Òåµ²°åÖÐÐÄÎ»ÖÃ
int radius,left,right;		//¶¨Òåµ²°å°ë¾¶£¬×óÓÒ±ß½ç
int bounce;		//¶¨Òå·´µ¯´ÎÊý
int score;		//¶¨Òå³É¼¨
int brick_x,brick_y;		//¶¨Òå×©¿éÎ»ÖÃ 

void gotoxy(int x,int y)	//¹â±êÒÆ¶¯µ½£¨x,y£©Î»ÖÃ 
{
	COORD pos = {x,y};
    HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleCursorPosition(hOut, pos);
} 

void hide()         //Òþ²Ø¹â±ê
{
	CONSOLE_CURSOR_INFO cursor_info = {1, 0};
	SetConsoleCursorInfo (GetStdHandle (STD_OUTPUT_HANDLE), &cursor_info);
}


void starup()		//Êý¾Ý³õÊ¼»¯ 
{
	high=34;
	width=18; 
	ball_x=1;
	ball_y=high/2;
	ball_vx=1;
	ball_vy=1;
	position_x=width;
	position_y=high/2;
	radius=5;
	left=position_x-radius;
	right=position_x+radius;
	bounce=0;
	brick_x=0;
	brick_y=4; 
	score=0; 
	hide(); 
}

void show()		//ÏÔÊ¾»­Ãæ 
{
	int i,j;
	gotoxy(0,0);
	for(i=0;i<=width+1;i++)
	{
		for(j=0;j<=high;j++)
		{
			if((i==ball_x)&&(j==ball_y))		//Êä³öÐ¡Çò 
				printf("o");
			else if(i==width+1)		//Êä³ö±ß¿ò 
				printf("-");
			else if(j==high)
				printf("|");
			else if((j<=right)&&(j>=left)&&(i==width))		//Êä³öµ²°å 
				printf("*");
			else if((i==brick_x)&&(j==brick_y))		//Êä³ö×©¿é 
				printf("#");
			else
				printf(" ");
		}
		printf("\n");
	}
	printf("·´µ¯Ð¡ÇòÊý£º%d\n",bounce); 
	printf("Ïû³ý×©¿éÊý£º%d\n",score); 
}

void updateWithoutInput()		//ÓëÓÃ»§ÊäÈëÎÞ¹ØµÄ¸üÐÂ 
{
	if(ball_x==width)		//¼ÇÂ¼·´µ¯´ÎÊý 
	{
		if((ball_y<=right)&&(ball_y>=left))
		{
			bounce++;
			ball_vy==-ball_vy;
		}
		else
		{	
			printf("Game over!");
			exit(0); 
		} 
	} 
	if(ball_x==0)
	{
		if(ball_y==brick_y)
		{
			score++;
			brick_y=rand()%width;
		}
	}
	ball_x=ball_x+ball_vx;
	ball_y=ball_y+ball_vy;
	if((ball_x==0)||(ball_x==width))
		ball_vx=-ball_vx;
	if((ball_y==0)||(ball_y==high))
		ball_vy=-ball_vy;
	Sleep(50);

}

void updateWithInput()		//ÓëÓÃ»§ÊäÈëÓÐ¹ØµÄ¸üÐÂ 
{
	char input;
	if(kbhit()) 		//µ±°´¼üÊ±Ö´ÐÐ 
	{
		input=getch();
		if(input=='a')
		{
			position_x--;
			left=position_x-radius;
			right=position_x+radius;
		} 
		if(input=='d')
		{
			position_x++;
			left=position_x-radius;
			right=position_x+radius;
		} 
	}
}

int main()
{
	starup();
	while(1)
	{
		show();
		updateWithoutInput();
		updateWithInput();
	}
	return 0;
}